﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Xml;
using System.Xml.Linq;

namespace Weber.CS3280.UI.ViewModels
{
	public abstract class ListingViewModelBase : ViewModelBase
	{
		private ICommand _addCommand;
		private ICommand _refreshViewCommand;
		private ViewModelBase[] _items;

		protected ListingViewModelBase()
		{
			_items = new ViewModelBase[0];
		}

		protected abstract void AddItem(Control control);

		protected virtual bool CanAddItem(Control control)
		{
			return true;
		}

		/// <summary>
		/// Gets a command defined for Adding a new record
		/// </summary>
		public ICommand AddCommand
		{
			get
			{
				if (_addCommand == null)
					_addCommand = new RelayCommand(p => AddItem(p as Control), p => CanAddItem(p as Control));

				return _addCommand;
			}
		}

		/// <summary>
		/// Gets a command defind for refreshing the list of items
		/// </summary>
		public ICommand RefreshViewCommand
		{
			get
			{
				if (_refreshViewCommand == null)
					_refreshViewCommand = new RelayCommand(p => RefreshView());

				return _refreshViewCommand;
			}
		}

		protected void RefreshView()
		{
			try
			{
				_items = GetItems();
				NotifyPropertyChanged("Items");
			}
			catch (Exception)
			{
				// Item list not updated
			}
		}

		public ViewModelBase[] Items
		{
			get { return _items; }
		}

		public void SendRefreshRequest()
		{
			RefreshView();
		}

		protected abstract ViewModelBase[] GetItems();
	}
}
